// 1. header 
let todoHeader = {
	template:'#todoheader',
	data() {
		return {
			inputVal: ""
		}
	},
	methods: {
		addTodo() {
			if(!this.inputVal) return
			this.$emit("add", this.inputVal)
			// 清空数据
			this.inputVal = ""
		}
	}
}

let todoList = {
	template:"#todolist",
	props: ["list"],
	directives: {
		focus(el, bindings) {
			if(bindings.value) {
				el.focus()
			}
		}
	},
	data() {
		return {
			isSelectAll: false,
			currentIndex: ''
		}
	},
	watch: {
		'list': {
			handler: function(newVal) {
				this.isSelectAll = newVal.every((item)=> {
					return item.isChecked === true
				})
			},
			deep: true
		}
	},
	methods: {
		joinEdit(index) {
			this.currentIndex = index
		},
		selectAll() {
			// 选中所有
			this.list.forEach((item)=> {
				item.isChecked = this.isSelectAll
			})
		},
		deleteTodo(index) {
			// 这种方式可以的
			this.list.splice(index, 1)

			// 这种方式不行。是因为重新给了list赋值了 -- warn
			// this.list = this.list.filter((item, i)=> {
			// 	return i !== index;
			// })
		}
	}
}

let todoFooter = {
	template: "#todofooter",
	props: ["list", "hash"],
	computed: {
		total() {
			return this.list.reduce((total, item)=> {
				if(item.isChecked) {
					return total
				}
				total++;
				return total
			}, 0)
		}
	}
}


const app = new Vue({
	el: ".todoapp",
	data:{
		todoListData: [],
		currentHash: ''
	},
	computed: {
		tempTodoList() {
			if(this.currentHash === "#/") {
				return this.todoListData
			}else if(this.currentHash === "#/active") {
				return this.todoListData.filter((item)=> {
					return item.isChecked===false
				})
			}else if(this.currentHash === "#/completed") {
				return this.todoListData.filter((item)=> {
					return item.isChecked===true
				})
			}else {
				return this.todoListData
			}
		}
	},
	created() {
		window.addEventListener("hashchange", ()=> {
			this.currentHash = window.location.hash
		})
	},
	methods: {
		// 添加数据完成
		addTodo(val) {
			this.todoListData.push({
				isChecked:false,
				text: val
			})
		}
	},
	components: {
		todoHeader,
		todoList,
		todoFooter
	}
})